import { $get } from '@js/authRequest'

// 获取呈批定义
export async function getFlowClass (flowKey) {
  const res = await $get(`/api/vendor/flow/bykey/${flowKey}`)
  if (res.status !== 1) {
    return new Error(res.message)
  }
  return res.data
}

// 获取指定key的呈批实例
export async function getFlowInstances (caseid, flowKey) {
  const res = await $get('/api/vendor/flowinstance', { caseid })
  if (res.status !== 1) {
    return new Error(res.message)
  }
  const instanceList = res.data.filter(li => li.flow_key === flowKey)
  await formatFlowInstance(instanceList)
  return instanceList
}

// 格式化呈批实例并加载对应的操作历史和当前操作步骤
function formatFlowInstance (instanceList) {
  return Promise.all(instanceList.map(li => {
    return Promise.all([initHistory(li), initCurrentStep(li)])
  }))
}

// 获取呈批实例的历史
export async function initHistory (instance) {
  const res = await $get('/api/vendor/flowinstance/action', {
    instanceid: instance.id
  })
  if (res.status !== 1) {
    return new Error(res.message)
  }
  res.data.sort((a, b) => a.create_datetime - b.create_datetime)
  instance.history = res.data
}

// 获取呈批实例的当前步骤
export async function initCurrentStep (instance) {
  const res = await $get(`/api/vendor/flowinstance/${instance.id}`)
  if (res.status !== 1) {
    return new Error(res.message)
  }
  instance.currentStep = res.data
}
